<!--
 * @Author: ChenYu ycyplus@gmail.com
 * @Date: 2025-09-08 
 * @Description: AI对话页面 - 固定底部输入框
-->
<template>
  <C_Layout
    :notification-count="notificationCount"
    @user-click="handleUserClick"
    @notification-click="handleNotificationClick"
    @settings-click="handleSettingsClick"
    @tab-change="handleTabChange"
  >
    <view class="chat-page">
      <!-- 页面头部 -->
      <view class="page-header">
        <view class="header-card">
          <view class="header-top">
            <view class="title-section">
              <C_Icon name="i-mdi-robot-excited" :size="32" color="white" />
              <text class="header-title">AI智能助手</text>
            </view>
            <!-- 模型选择 -->
            <picker 
              :value="selectedModelIndex" 
              :range="modelOptions"
              range-key="name"
              @change="onModelChange"
            >
              <view class="model-tag">
                <text class="model-name">{{ currentModel.name }}</text>
                <view class="status-dot"></view>
              </view>
            </picker>
          </view>
          <text class="header-desc">与AI进行智能对话，获取专业解答</text>
        </view>
      </view>

      <!-- 消息区域 - 预留底部空间 -->
      <scroll-view 
        class="messages-container" 
        scroll-y="true" 
        :scroll-top="scrollTop"
        enhanced
        show-scrollbar="false"
      >
        <view class="messages-wrapper">
          <!-- 欢迎消息 -->
          <view v-if="messages.length === 0" class="welcome-message">
            <view class="ai-message-item">
              <view class="ai-avatar">
                <C_Icon name="i-mdi-robot" :size="20" color="#666" />
              </view>
              <view class="message-bubble ai-bubble">
                <text class="message-text">你好！我是AI助手，有什么可以帮助您的吗？</text>
              </view>
            </view>
          </view>

          <!-- 聊天消息 -->
          <view class="chat-messages">
            <template v-for="message in messages" :key="message.id">
              <!-- 用户消息 -->
              <view v-if="message.isUser" class="message-item user-message">
                <view class="message-bubble user-bubble">
                  <text class="message-text">{{ message.content }}</text>
                  <text class="message-time">{{ message.timestamp }}</text>
                </view>
              </view>
              
              <!-- AI消息 -->
              <view v-else class="message-item ai-message-item">
                <view class="ai-avatar">
                  <C_Icon name="i-mdi-robot" :size="20" color="#666" />
                </view>
                <view class="message-bubble ai-bubble">
                  <text class="message-text">{{ message.content }}</text>
                  <text class="message-time">{{ message.timestamp }}</text>
                </view>
              </view>
            </template>

            <!-- AI思考中 -->
            <view v-if="isThinking" class="message-item ai-message-item">
              <view class="ai-avatar">
                <C_Icon name="i-mdi-robot" :size="20" color="#666" />
              </view>
              <view class="message-bubble ai-bubble thinking-bubble">
                <view class="typing-dots">
                  <view class="dot"></view>
                  <view class="dot"></view>
                  <view class="dot"></view>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 底部占位，避免最后一条消息被输入框遮挡 -->
          <view class="bottom-spacer"></view>
        </view>
      </scroll-view>
    </view>

    <!-- 固定底部输入框 -->
    <view class="fixed-input-area">
      <view class="input-wrapper">
        <view class="input-row">
          <textarea 
            v-model="inputText" 
            class="message-input"
            placeholder="请输入消息..."
            placeholder-class="input-placeholder"
            :maxlength="500"
            auto-height
            @input="handleInput"
            @confirm="sendMessage"
            @focus="onInputFocus"
            @blur="onInputBlur"
          />
          <view class="send-button" @click="sendMessage" :class="{ active: canSend }">
            <view v-if="isThinking" class="loading-icon">
              <u-loading-icon mode="flower" size="16" color="#fff"></u-loading-icon>
            </view>
            <C_Icon v-else name="i-mdi-send" :size="18" :color="canSend ? '#fff' : '#999'" />
          </view>
        </view>
        <view class="input-info">
          <text class="char-count">{{ inputText.length }}/500</text>
        </view>
      </view>
    </view>
  </C_Layout>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'

const notificationCount = ref(0)
const messages = ref([])
const inputText = ref('')
const isThinking = ref(false)
const scrollTop = ref(0)
const selectedModelIndex = ref(0)
const isInputFocused = ref(false)

// 模型选项
const modelOptions = ref([
  { name: 'DeepSeek-V3', id: 'deepseek' },
  { name: 'GPT-4o', id: 'gpt4' },
  { name: 'Claude-3.5', id: 'claude' },
  { name: 'Gemini-Pro', id: 'gemini' }
])

// 计算属性
const currentModel = computed(() => modelOptions.value[selectedModelIndex.value])
const canSend = computed(() => inputText.value.trim().length > 0 && !isThinking.value)

// 处理输入
const handleInput = (e) => {
  inputText.value = e.detail.value
}

// 输入框焦点事件
const onInputFocus = () => {
  isInputFocused.value = true
}

const onInputBlur = () => {
  isInputFocused.value = false
}

// 发送消息
const sendMessage = async () => {
  if (!canSend.value) return
  
  const content = inputText.value.trim()
  if (!content) return

  // 添加用户消息
  const userMessage = {
    id: Date.now(),
    content,
    isUser: true,
    timestamp: getCurrentTime()
  }
  messages.value.push(userMessage)
  inputText.value = ''

  // 滚动到底部
  await scrollToBottom()
  
  // AI思考
  isThinking.value = true
  
  // 模拟AI回复
  setTimeout(async () => {
    isThinking.value = false
    
    const aiReply = generateReply(content)
    const aiMessage = {
      id: Date.now() + 1,
      content: aiReply,
      isUser: false,
      timestamp: getCurrentTime()
    }
    
    messages.value.push(aiMessage)
    await scrollToBottom()
  }, 1000 + Math.random() * 2000)
}

// 生成AI回复
const generateReply = (userInput) => {
  const input = userInput.toLowerCase()
  
  if (input.includes('你好') || input.includes('hi') || input.includes('hello')) {
    return '你好！很高兴见到你！有什么可以帮助的吗？'
  } else if (input.includes('谢谢') || input.includes('感谢')) {
    return '不客气！很高兴能够帮助到您'
  } else if (input.includes('帮助') || input.includes('help')) {
    return '我可以帮您：\n\n• 回答问题和解释概念\n• 协助编程和代码调试\n• 翻译和写作辅助\n• 学习指导和知识答疑\n\n请告诉我您需要什么帮助！'
  } else if (input.includes('代码') || input.includes('编程') || input.includes('程序')) {
    return '我很擅长编程！请告诉我：\n\n• 使用什么编程语言？\n• 要实现什么功能？\n• 遇到了什么问题？\n\n我会尽力帮助您解决编程问题！'
  } else if (input.includes('再见') || input.includes('拜拜') || input.includes('bye')) {
    return '再见！期待下次与您交流！'
  } else {
    const replies = [
      '这是个很有趣的问题！让我来分析一下...',
      '我理解您的意思，这确实值得深入探讨。',
      '根据您的描述，我有以下建议...',
      '让我为您详细解答这个问题。',
      '您提出了一个很好的观点！我来补充一些信息。',
      '这个话题很有价值，我来从不同角度分析一下。'
    ]
    return replies[Math.floor(Math.random() * replies.length)]
  }
}

// 模型切换
const onModelChange = (e) => {
  selectedModelIndex.value = e.detail.value
  uni.showToast({
    title: `已切换到 ${currentModel.value.name}`,
    icon: 'none'
  })
}

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date()
  return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  scrollTop.value = scrollTop.value === 99999 ? 99998 : 99999
}

// 事件处理函数
const handleUserClick = () => uni.showToast({ title: '用户信息', icon: 'none' })
const handleNotificationClick = () => uni.showToast({ title: '通知', icon: 'none' })
const handleSettingsClick = () => uni.showToast({ title: '设置', icon: 'none' })
const handleTabChange = ({ item, index }) => console.log('标签切换:', item.text, index)
</script>

<style lang="scss" scoped>
.chat-page {
  background: #f5f7fa;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

// 头部样式
.page-header {
  padding: 20rpx;
  flex-shrink: 0;
}

.header-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16rpx;
  padding: 32rpx;
  color: white;
}

.header-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.title-section {
  display: flex;
  align-items: center;
}

.header-title {
  color: white;
  font-size: 36rpx;
  font-weight: bold;
  margin-left: 20rpx;
}

.header-desc {
  color: rgba(255, 255, 255, 0.9);
  font-size: 28rpx;
  opacity: 0.9;
}

.model-tag {
  background: rgba(255, 255, 255, 0.25);
  padding: 12rpx 20rpx;
  border-radius: 24rpx;
  display: flex;
  align-items: center;
  gap: 12rpx;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.model-name {
  color: white;
  font-size: 26rpx;
  font-weight: 500;
}

.status-dot {
  width: 10rpx;
  height: 10rpx;
  background: #4ade80;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

// 消息区域 - 预留底部空间给固定输入框
.messages-container {
  flex: 1;
  background: white;
  margin: 0 20rpx;
  border-radius: 16rpx 16rpx 0 0;
  padding-bottom: 200rpx; // 为固定输入框预留空间
}

.messages-wrapper {
  padding: 30rpx;
  min-height: 100%;
}

.bottom-spacer {
  height: 40rpx; // 额外底部间距
}

// 消息样式
.message-item {
  margin-bottom: 32rpx;
  
  &.user-message {
    display: flex;
    justify-content: flex-end;
  }
  
  &.ai-message-item {
    display: flex;
    align-items: flex-start;
    gap: 20rpx;
  }
}

.welcome-message {
  .ai-message-item {
    display: flex;
    align-items: flex-start;
    gap: 20rpx;
  }
}

.ai-avatar {
  width: 68rpx;
  height: 68rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  border: 2rpx solid #dee2e6;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.message-bubble {
  max-width: 70%;
  padding: 28rpx 32rpx;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  position: relative;
  
  &.user-bubble {
    background: linear-gradient(135deg, #007aff, #0056d3);
    color: white;
    border-bottom-right-radius: 8rpx;
  }
  
  &.ai-bubble {
    background: #f8f9fa;
    color: #333;
    border: 1rpx solid #e9ecef;
    border-bottom-left-radius: 8rpx;
    max-width: calc(70% - 88rpx);
  }
}

.message-text {
  font-size: 32rpx;
  line-height: 1.6;
  word-wrap: break-word;
  white-space: pre-wrap;
  color: inherit;
}

.message-time {
  font-size: 24rpx;
  margin-top: 12rpx;
  display: block;
  text-align: right;
  opacity: 0.7;
}

// AI思考动画
.thinking-bubble {
  padding: 24rpx 32rpx;
}

.typing-dots {
  display: flex;
  gap: 8rpx;
  align-items: center;
}

.dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background: #999;
  animation: typing 1.4s ease-in-out infinite both;

  &:nth-child(1) { animation-delay: -0.32s; }
  &:nth-child(2) { animation-delay: -0.16s; }
  &:nth-child(3) { animation-delay: 0s; }
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.4;
  }
  30% {
    transform: translateY(-10rpx);
    opacity: 1;
  }
}

// 固定底部输入框
.fixed-input-area {
  position: fixed;
  bottom: 100rpx; // tabbar高度，通常是100rpx
  left: 0;
  right: 0;
  background: white;
  border-top: 1rpx solid #e5e7eb;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
  z-index: 999;
}

.input-wrapper {
  padding: 20rpx 24rpx;
}

.input-row {
  display: flex;
  align-items: flex-end;
  gap: 16rpx;
  background: #f8f9fa;
  border: 2rpx solid #e5e7eb;
  border-radius: 24rpx;
  padding: 16rpx 20rpx;
  transition: all 0.3s ease;
  
  &:focus-within {
    border-color: #007aff;
    background: white;
    box-shadow: 0 0 0 4rpx rgba(0, 122, 255, 0.1);
  }
}

.message-input {
  flex: 1;
  min-height: 60rpx;
  max-height: 160rpx;
  font-size: 32rpx;
  line-height: 1.5;
  color: #333;
  background: transparent;
  border: none;
  outline: none;
}

.input-placeholder {
  color: #999 !important;
  font-size: 32rpx !important;
}

.send-button {
  width: 64rpx;
  height: 64rpx;
  border-radius: 32rpx;
  background: #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  flex-shrink: 0;
  
  &.active {
    background: linear-gradient(135deg, #007aff, #0056d3);
    transform: scale(1.05);
    box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
    
    &:active {
      transform: scale(0.98);
    }
  }
}

.loading-icon {
  display: flex;
  align-items: center;
  justify-content: center;
}

.input-info {
  display: flex;
  justify-content: flex-end;
  margin-top: 12rpx;
  padding: 0 8rpx;
}

.char-count {
  font-size: 24rpx;
  color: #999;
}

// 响应式适配
@media (max-width: 750rpx) {
  .message-bubble {
    max-width: 85%;
    
    &.ai-bubble {
      max-width: calc(85% - 88rpx);
    }
  }
  
  .header-title {
    font-size: 32rpx;
  }
  
  .fixed-input-area {
    bottom: 98rpx; // 小屏幕tabbar可能稍低
  }
}
</style>